import { ActionFunctionArgs, redirect } from 'react-router-dom'

export default async ({ request }: ActionFunctionArgs) => {
  const formData = await request.formData()
  const data = Object.fromEntries(formData)
  switch (formData.get('action')) {
    case 'add': {
      return await window.api.sql(
        `insert into categories (name,created_at) values('未命名',datetime()) `,
        'insert',
      )
    }
    case 'remove': {
      await window.api.sql(`delete from categories where id=@id`, 'del', { id: data.id })
      // 已删除栏目下的content修改为未分类栏目下
      await window.api.sql(
        `update contents set category_id=0 where category_id=@category_id`,
        'update',
        { category_id: data.id },
      )
      return redirect(`/config/category/contentList`)
    }
    case 'update': {
      await window.api.sql(`update categories set name=@name where id=@id`, 'update', {
        id: data.id,
        name: data.name,
      })
      // return redirect(`/config/category/contentList/${data.id}`)
    }
  }
  return {}
}
